429A - Xor-tree - CodeForces Solution


dfs and similar trees *1300

Please click on ads to support us..

Python Code:

n = int(input())
adj_list = {i: [] for i in range(n)}
 
for edge in range(n-1):
    a, b = list(map(int, input().split()))
    adj_list[a-1].append(b-1)
    adj_list[b-1].append(a-1)
 
v = list(map(int, input().split()))
d = list(map(int, input().split()))
 
ans = 0
queue = [[0, 0, 0, 0]] visited = [0 for i in range(n)]
visited[0] = 1
 
lst = []
 
while len(queue) != 0:
    node, even, odd, level = queue.pop()
    if level == 0:
        if (even == 0 and v[node] != d[node]) or (even == 1 and v[node] == d[node]):
            ans += 1
            even = 1 - even
            lst.append(node + 1)
    else:
        if (odd == 0 and v[node] != d[node]) or (odd == 1 and v[node] == d[node]):
            ans += 1
            odd = 1 - odd
            lst.append(node + 1)
    level = 1 - level
 
    for son in adj_list[node]:
        if (visited[son] == 0):
            visited[son] = 1
            queue.append([son, even, odd, level])
 
print(ans)
for i in lst:
    print(i)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
int init[100005],goal[100005];
vector<int>g[100005],ans;
void dfs(int v,int p,int odd,int even,int h){
	if(h%2==1){
		if(odd==1) init[v]=1-init[v];
		if(init[v]!=goal[v]) ans.pb(v),odd=1-odd;
	}
	else{
		if(even==1) init[v]=1-init[v];
		if(init[v]!=goal[v]) ans.pb(v),even=1-even;
	}
	for(auto it:g[v])
		if(it!=p) dfs(it,v,odd,even,h+1);
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
	int i,n;
	cin>>n;
	for(i=1;i<=n-1;i++){
		int a,b;
		cin>>a>>b;
		g[a].pb(b);
		g[b].pb(a);
	}
	for(i=1;i<=n;i++) cin>>init[i];
	for(i=1;i<=n;i++) cin>>goal[i];
	dfs(1,0,0,0,1);
	cout<<ans.size()<<'\n';
	for(auto it:ans) cout<<it<<'\n';
}


Comments

Submit
0 Comments
More Questions

32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation
893C - Rumor
227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General
1106A - Lunar New Year and Cross Counting
58A - Chat room